﻿using Frogsoft.Data;
using Frogsoft.Domain.Permission;
using Frogsoft.Permission.Dtos;
using Frogsoft.Permission.ShareDtos;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Frogsoft.Permission
{
    public class RoleService
    {
        private MyContext _myContext;
        private RoleManager<IdentityRole>? _roleManager;
        public RoleService(MyContext myContext, RoleManager<IdentityRole>? roleManager)
        {
            _myContext = myContext;
            _roleManager = roleManager;
        }

        public IQueryable<AppRoleDto> GetAll()
        {
            return _myContext.Roles.OrderBy(o=>o.Name).Select(s => new AppRoleDto { Id = s.Id, RoleName = s.Name }).AsQueryable();
        }

        public Result<List<AppRoleDto>> GetAllPageing(int page, int limit)
        {
            var total = _myContext.Roles.Count();
            var data = _myContext.Roles.OrderBy(s => s.Id).Skip((page - 1) * limit).Take(limit).Select(o => new AppRoleDto { Id = o.Id, RoleName = o.Name }).ToList();
            return new Result<List<AppRoleDto>>(0, total, data);
        }

        public AppRoleDto Create(AppRoleDto appRoleDto)
        {
            var role = new IdentityRole();
            role.Name = appRoleDto.RoleName;
            var result = _roleManager.CreateAsync(role).Result;
            if (result.Succeeded)
            {
                return appRoleDto;
            }
            else
            {
                throw new Exception("角色创建失败");
            }
        }

        public async Task<string> Delete(string roleId)
        {
            var role = await _roleManager.FindByIdAsync(roleId);
            var result = await _roleManager.DeleteAsync(role);
            return "ok";
        }

        public AppRoleDto Update(AppRoleDto appRoleDto)
        {
            var role = _roleManager.FindByIdAsync(appRoleDto.Id).Result;
            role.Name = appRoleDto.RoleName;
            var result = _roleManager.UpdateAsync(role).Result;
            if (result.Succeeded)
            {
                return appRoleDto;
            }
            else
            {
                throw new Exception("用户更新失败");
            }
        }

        public AppRoleDto GetById(string id)
        {
            return _myContext.Roles.Where(x => x.Id == id).Select(o => new AppRoleDto { Id = o.Id, RoleName = o.Name }).FirstOrDefault();
        }
    }
}
